<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/4/19
 * Time: 15:57
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class Coupon extends Base {
    public function index(){
        extract(input());
        if(request()->isAjax()){
            extract(input());
            $where = array();
            if(isset($s_id) && $s_id != ''){
                $where['coupon_s_id'] = $s_id;
            }
            $params = input('param.');
            $where['coupon_status'] = array('NEQ',4);
            if(isset($params['coupon_status']) && $params['coupon_status'] != '')
            {
                $where['coupon_status'] = $params['coupon_status'];
            }
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['coupon_name|s_name'] = ['like', "%" . $params['key'] . "%"];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_shop_coupon')->alias('a')
                ->join('up_shops us','us.s_id = a.coupon_s_id','left')
                ->where($where)->count();// 获取总条数
            $lists = Db::name('shop_coupon')->alias('a')
                ->where($where)
                ->join('up_shops us','us.s_id = a.coupon_s_id','left')
                ->page($Nowpage,$limits)
                ->field('a.*,us.s_name,us.s_phone')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        if(!isset($s_id) || empty($s_id)){
            $s_id = '';
        }
        $this->assign('s_id',$s_id);
        return $this->fetch();
    }


    //删除
    public function del(){
        $id = input('param.id');
        $where['coupon_id'] = $id;
        $info = Db::table('up_shop_coupon')->where($where)->find();
        if($info['coupon_status']==1){
            return json(['code'=>100,'msg'=>'不能删除上架的优惠券，请先下架优惠券']);
        }
        $data['coupon_status'] = 4;
        $res = Db::table('up_shop_coupon')->where($where)->update($data);
        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }


    //下架
    public function lower(){
        $id = input('param.id');
        $where['coupon_id'] = $id;
        $can = Db::table('up_shop_coupon')->where($where)->find();
        if($can['coupon_status'] != 1){
            return json(['code'=>100,'msg'=>'此优惠券已经下架']);
        }
        Db::startTrans ();
        try{
            $today = date('Y-m-d H:i:s');
            $update = [
                'coupon_time' => $today,
                'coupon_status' => 3, //1上架  3下架
            ];
            if($can['coupon_status'] != 1){
                return json(['status'=>0,'msg'=>'只有上架的卡券才可以下架']);
            }
            $back = ($can['coupon_num'] - $can['coupon_get_num']) * $can['coupon_price'];
            if ($back > 0) {
                Db::name('shops')
                    ->where('s_id', $can['coupon_s_id'])
                    ->setInc('s_money', $back);
                //入商户明细和商户消息
                allInShopDetail($back, 2, $can['coupon_s_id'], $can['coupon_name'] . '优惠券下架退还',8);
                allInNotice('优惠券下架退还', $can['coupon_name'] . '优惠券下架退还，返还' . ($back / 10) . '元！', 3, $can['coupon_s_id']);
            }
            Db::table('up_shop_coupon')->where('coupon_id',$id)->update($update);
            Db::commit();
            return json(['code' => 200, 'msg' => '成功']);
        }catch (\Exception $e){
            Db::rollback ();
            return json(['code'=>100,'msg'=>'失败']);
        }
    }


    //查看
    public function detail(){
        if(request()->isAjax()){
            $where = array();
            $id = input('param.id');
            $params = input('param.');
            $where['mc_coupon_id'] = $id;
            if(isset($params['mc_send']) && $params['mc_send'] != '')
            {
                $where['mc_send'] = $params['mc_send'];
            }
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['coupon_name|mc_code|u.user_phone|u2.user_phone'] = ['like', "%" . $params['key'] . "%"];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_my_shop_coupon')->alias('c')
                ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
                ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
                ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $field = 'c.*';
            $field .= ',u.user_username,u.user_phone,u2.user_username user_username2,u2.user_phone user_phone2';
            $field .= ',coupon_name,coupon_image';
            $lists = Db::table('up_my_shop_coupon')->alias('c')
                ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
                ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
                ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
                ->where($where)
                ->order('mc_time DESC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $this->assign('id',input('id'));
        return $this->fetch();
    }
    //查看
    public function couponuse(){
        if(request()->isAjax()){
            $where = array();
            $params = input('param.');
            if(isset($params['mc_send']) && $params['mc_send'] != '')
            {
                $where['mc_send'] = $params['mc_send'];
            }
            if(isset($params['mc_status']) && $params['mc_status'] != '')
            {
                $where['mc_status'] = $params['mc_status'];
            }
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['coupon_name|mc_code|u.user_phone|u2.user_phone'] = ['like', "%" . $params['key'] . "%"];
            }
            if(isset($params['key2']) && $params['key2'] != '')
            {
                $where['s_name|s_phone'] = ['like', "%" . $params['key2'] . "%"];
            }
            if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']=="")
            {
                $where['mc_use_time'] = ['>= time',$params['start']];
            }
            if(isset($params['end'])&&$params['end']!=""&&isset($params['start'])&&$params['start']=="")
            {
                $where['mc_use_time'] = ['<= time',$params['end']];
            }
            if(isset($params['start'])&&$params['start']!=""&&isset($params['end'])&&$params['end']!="")
            {
                $where['mc_use_time'] = ['between time',[$params['start'],$params['end']]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_my_shop_coupon')->alias('c')
                ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
                ->join('up_shops s','c.mc_s_id=s.s_id','LEFT')
                ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
                ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $field = 'c.*';
            $field .= ',u.user_username,u.user_phone,u2.user_username user_username2,u2.user_phone user_phone2';
            $field .= ',coupon_name,coupon_image,s_name,s_phone';
            $lists = Db::table('up_my_shop_coupon')->alias('c')
                ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
                ->join('up_shops s','c.mc_s_id=s.s_id','LEFT')
                ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
                ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
                ->where($where)
                ->order('mc_time DESC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }

    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function excelCoupon(){
        extract(input());
        $where = [
            'coupon_status' => ['<>',4]
        ];
        if($name){
            $where['coupon_name'] = ['like',"%" . $name . "%"];
        }
        if($type){
            $where['coupon_status'] = $type;
        }
        if($s_id){
            $where['coupon_s_id'] = $s_id;
        }
        $data = Db::table('up_shop_coupon')->alias('a')
            ->join('up_shops us','us.s_id = a.coupon_s_id','left')
            ->where($where)
            ->field('a.*,us.s_name,us.s_phone')
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                if($v['coupon_status'] == 1){
                    $data[$k]['coupon_status'] = '上架';
                }
                if($v['coupon_status'] == 2){
                    $data[$k]['coupon_status'] = '已到期';
                }
                if($v['coupon_status'] == 3){
                    $data[$k]['coupon_status'] = '下架';
                }
            }
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
        $cellname = [
            ['s_name','商家名称',30,'LEFT'],
            ['s_phone','商家电话',30,'LEFT'],
            ['coupon_name','名称',30,'LEFT'],
            ['coupon_num','数量',15,'LEFT'],
            ['coupon_price','兑换价格',20,'LEFT'],
            ['coupon_money','面额',15,'LEFT'],
            ['coupon_get_num','领取数量',15,'LEFT'],
            ['coupon_use_num','核销数量',15,'LEFT'],
            ['coupon_start','领取开始日期',15,'LEFT'],
            ['coupon_end','领取结束日期',15,'LEFT'],
            ['coupon_use_day','领取使用期限(天)',15,'LEFT'],
            ['coupon_time','发布时间',15,'LEFT'],
            ['coupon_status','状态',15,'LEFT'],
        ];
        $res = exportExcel('卡券数据','coupon',$cellname,$data);
        return json($res);
    }


}